# -*- coding: UTF-8 -*-

import cv2
import dlib
import numpy as np
from skimage import exposure

predictor_path = r"../model/shape_predictor_68_face_landmarks.dat"#提取68个点
# 初始化
predictor = dlib.shape_predictor(predictor_path)
# 初始化dlib人脸检测器
detector = dlib.get_frontal_face_detector()


class predo:
    def __init__(self,path):
        self.path=path
        self.img = cv2.imread(self.path)
        self.face= detector(self.img, 0)
    def get_position(self,ps):
        delta = 0.2
        xmin = min(ps, key=lambda x: x[0])
        xmax = max(ps, key=lambda x: x[0])
        ymin = min(ps, key=lambda x: x[1])
        ymax = max(ps, key=lambda x: x[1])
        w = xmax[0] - xmin[0]
        h = ymax[1] - ymin[1]
        xmin = int(xmin[0] - delta * w)
        xmax = int(xmax[0] + delta * w)
        ymin = int(ymin[1] - delta * h)
        ymax = int(ymax[1] + delta * h)
        return xmin, xmax, ymin, ymax

    def output2Fold(self):#对于人脸进行分割处理（赖志立的要求）
        # cur_index = os.listdir(output_path).__len__()
        output_img = []
        for num, d in enumerate(self.face):
            output_img = self.img[d.top():d.bottom(), d.left():d.right()]
        cv2.normalize(output_img, output_img, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
        output_img = exposure.adjust_gamma(output_img, 1.5)  # 伽马处理
        return output_img

    def gan(self):#单独分割鼻子
        img_nose=[]
        dets = detector(self.img, 0)
        for k, d in enumerate(dets):
            # get points
            shape = predictor(self.img, d)
            points = [[item.x, item.y] for item in shape.parts()]
            nose = np.array(points[28:36], dtype=np.int32)
            x1, x2, y1, y2 = self.get_position(nose)
            img_nose = self.img[y1:y2, x1:x2]
        cv2.normalize(img_nose, img_nose, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)  # 均衡化
        img_nose = exposure.adjust_gamma(img_nose, 1.5)
        
        return  img_nose

